package com.yu.yupicture.api.aliyunApi.sub;


import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.yu.yupicture.api.aliyunApi.model.ImageEditRequest;
import com.yu.yupicture.api.aliyunApi.model.ImageEditResponse;
import com.yu.yupicture.api.aliyunApi.model.ImageGetResponse;
import com.yu.yupicture.exception.ErrorCode;
import com.yu.yupicture.exception.biusnessException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 扩图api
 */

@Slf4j
@Data
@Component
public class aliImageEditRequestApi {

    @Value("${aliyun.Apikey}")
    private  String Apikey;

    //发送请求地址
    private static final String SEND_REQUEST_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/out-painting";
    //请求结果 地址
    private static final String GET_RESULT_URL = "https://dashscope.aliyuncs.com/api/v1/tasks/%s";

    //发送请求
    public  ImageEditResponse sendRequest(ImageEditRequest request) {
        log.info("调用阿里api,apikey:{}", Apikey);
        /**
         * curl --location 'https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/image-synthesis' \
         * --header 'X-DashScope-Async: enable' \
         * --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
         * --header 'Content-Type: application/json' \
         * --data '{
         *   "model": "wanx2.1-imageedit",
         *   "input": {
         *     "function": "expand",
         *     "prompt": "一位绿色仙子",
         *     "base_image_url": "http://wanx.alicdn.com/material/20250318/expand_2.jpg"
         *   },
         *   "parameters": {
         *     "top_scale": 1.5,
         *     "bottom_scale": 1.5,
         *     "left_scale": 1.5,
         *     "right_scale": 1.5,
         *     "n": 1
         *   }
         */
        HttpRequest httpRequest = HttpRequest.post(SEND_REQUEST_URL)
                .header("X-DashScope-Async", "enable")
                .header("Authorization", "Bearer " + Apikey)
                .header("Content-Type", "application/json")
                .body(JSONUtil.toJsonStr(request));

        try (HttpResponse response = httpRequest.execute()) {
            if (!response.isOk()) {
                log.error("调用阿里api失败,response:{}", response.body());
                throw new biusnessException(ErrorCode.OPERATION_ERROR, "调用阿里api失败");
            }
            String responseBody = response.body();
            ImageEditResponse imageEditResponse = JSONUtil.toBean(responseBody, ImageEditResponse.class);
            if (imageEditResponse == null ) {
                log.error("调用阿里api失败,response:{}", responseBody);
                throw new biusnessException(ErrorCode.OPERATION_ERROR, "调用阿里api失败");
            }
            if (imageEditResponse.getOutput() == null|| imageEditResponse.getOutput().getTaskId() == null) {
                log.error("调用阿里api失败,response:{}", responseBody);
                throw new biusnessException(ErrorCode.OPERATION_ERROR, "调用阿里api失败");
            }
            if (imageEditResponse.getCode() != null) {
                String message = imageEditResponse.getMessage();
                log.error("调用阿里api失败,response:{},errmessage:{}", responseBody, message);
                throw new biusnessException(ErrorCode.OPERATION_ERROR, message);
            }
            log.info("调用阿里api成功,imageEditResponse:{}", imageEditResponse);
            return imageEditResponse;
        } catch (Exception e) {
            log.error("调用阿里api失败", e);
            throw new biusnessException(ErrorCode.OPERATION_ERROR, "调用阿里api失败");
        }
    }

    //查询结果
    public  ImageGetResponse getResult(String taskId) {
        HttpRequest httpRequest = HttpRequest.get(String.format(GET_RESULT_URL, taskId))
                .header("Authorization", "Bearer " + Apikey);
        try (HttpResponse response = httpRequest.execute()) {
            if (!response.isOk()) {
                log.error("调用阿里api失败,response:{}", response.body());
                throw new biusnessException(ErrorCode.OPERATION_ERROR, "调用阿里api失败");
            }
            String responseBody = response.body();
            ImageGetResponse imageGetResponse = JSONUtil.toBean(responseBody, ImageGetResponse.class);
            if (imageGetResponse == null ) {
                log.error("调用阿里api失败,response:{}", responseBody);
                throw new biusnessException(ErrorCode.OPERATION_ERROR, "调用阿里api失败");
            }
            if (imageGetResponse.getOutput().getCode() != null) {
                String message = imageGetResponse.getOutput().getMessage();
                log.error("调用阿里api失败,response:{},errmessage:{}", responseBody, message);
                throw new biusnessException(ErrorCode.OPERATION_ERROR, message);
            }
            log.info("调用阿里api成功,imageGetResponse:{}", imageGetResponse);
            return imageGetResponse;
        }catch (Exception e){
            throw new biusnessException(ErrorCode.OPERATION_ERROR, "调用阿里api失败");
        }
    }
}
